import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:ost_flutter_module/class/entity/store/store_search_entity.dart';
import 'package:ost_flutter_module/main.dart';
import 'package:ost_flutter_module/network/base_request_model.dart';
import 'package:ost_flutter_module/network/completable_action.dart';
import 'package:ost_flutter_module/network/http_manager.dart';
import 'package:ost_flutter_module/network/url_constants.dart';
import 'package:ost_flutter_module/widget/loading/loading_view.dart';
import 'package:uuid/uuid.dart';

part 'store_search_event.dart';
part 'store_search_state.dart';

class StoreSearchBloc extends Bloc<StoreSearchEvent, StoreSearchState> {
  StoreSearchBloc() : super(StoreSearchInitial());

  BaseRequestModel<StoreSearchEntity> _dataModel =
      BaseRequestModel<StoreSearchEntity>();
  BaseRequestModel<StoreSearchEntity> get dataModel => _dataModel;

  @override
  Stream<StoreSearchState> mapEventToState(
    StoreSearchEvent event,
  ) async* {
    if (event is StoreSearchFetchEvent) {
      yield* _mapFetch(event, action: event.action);
    }
  }

  Stream<StoreSearchSuccess> _mapFetch(
    StoreSearchFetchEvent event, {
    CompletableAction action,
  }) async* {
    var result = await HttpManager.getInstance().syncRequest<StoreSearchEntity>(
      store_search,
      baseUrl: BASE_URL_MALL,
      params: {
        'city': event.city,
        'query': event.query,
        'point': event.point,
        'tagId': event.tagId,
      },
    );

    action?.completer?.complete(true);

    logger.i(result);

    if (result.isSuccess) {
      var data = result.getOrNull;
      _dataModel = _dataModel.copyWith(
        loadingStatus:
            data != null ? LoadingStatus.success : LoadingStatus.empty,
        entity: data,
      );
    } else {
      _dataModel = _dataModel.copyWith(
        loadingStatus: LoadingStatus.error,
        errorMsg: result.exceptionOrNull?.showMsg,
      );
    }

    yield StoreSearchSuccess(Uuid().v4());
  }
}
